const express = require('express');
const router = express.Router();
const saveIp = require('../config/save-ip');
const DomainIp = require('../domain-ip');
const config = require('../config');
const messageNum = require('./messagenum');
const url = require('url');
const domainIps = saveIp.map(function (val) {
  return new DomainIp(val);
})

/**
 * 健康检查
 */
router.get('/health', function (req, res) {
  res.end(config.randId + ' is ok,' + messageNum.getNum() +',time:' + new Date().getTime())
})

/**
 * 拦截器
 */
router.use(function (req, res, next) {
  const referer = req.headers.referer;
  if (!referer) return res.end();
  const myUrl = url.parse(referer)
  const result = domainIps.findIndex(function (domainIp) {
    return domainIp.isIn(myUrl.hostname)
  })
  if (result === -1) return res.end();

  //--- 跨越请求 ---
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials", "true")
  res.header("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,X-AUTH-TOKEN");
  // 浏览器是会先发一次options请求，如果请求通过，则继续发送正式的post请求
  // 配置options的请求返回
  if (req.method == "OPTIONS") {
    res.sendStatus(200);
    return res.end("OPTIONS returns OK");
  }
  req.data = Object.assign({}, req.query, req.body);
  if (config.env.indexOf(req.data.env) < 0) return res.end();
  next();
});


// 收集日志
router.use(require('./collect'));

module.exports = router;